﻿#include <winsock2.h>
#include <stdio.h>
#include "mstcpip.h"
#pragma comment(lib,"ws2_32.lib")
int getallIP()
{
   ////////////////
   // 初始化 Windows sockets API.
   //
   WORD wVersionRequested = MAKEWORD(2, 2);
   WSADATA wsaData;
   if (WSAStartup(wVersionRequested, &wsaData)) {
      printf("WSAStartup failed %s\n", WSAGetLastError());
      return 0;
   }

   //////////////////
   // 获得主机名.
   //
   char hostname[256];
   int res = gethostname(hostname, sizeof(hostname));
   if (res != 0) {
      printf("Error: %u\n", WSAGetLastError());
      return 0;
   }
   printf("hostname=%s\n", hostname);
   ////////////////
   // 根据主机名获取主机信息. 
   //
   hostent* pHostent = gethostbyname(hostname);
   if (pHostent==NULL) {
      printf("Error: %u\n", WSAGetLastError());
      return 0;
   }
   //////////////////
   // 解析返回的hostent信息.
   //
   hostent& he = *pHostent;
   printf("name=%s\naliases=%s\naddrtype=%d\nlength=%d\n",
      he.h_name, he.h_aliases, he.h_addrtype, he.h_length);
   
   sockaddr_in sa;
   //根据 he.h_addr_list[nAdapter]是否为空来获取所有IP地址
   for (int nAdapter=0; he.h_addr_list[nAdapter]; nAdapter++) {
      memcpy ( &sa.sin_addr.s_addr, he.h_addr_list[nAdapter],he.h_length);
      // 输出机器的IP地址.
      printf("Address [%d%]: %s\n",nAdapter, inet_ntoa(sa.sin_addr)); // 显示地址串
   }
   //////////////////
   // 终止 Windows sockets API
   //
   WSACleanup();
   return 0;
}     